<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="springmvc," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="配置MultipartResolver实现文件上传，SpringMVC专门提供了CommonsMultipartResolver组件用于文件上传：

maxUploadSize    文件最大限制，单位是byte
maxInMemorySize     低于这个大小的文件暂存内存中
defaultEncoding    默认编码

&amp;lt;!--文件上传的组件--&amp;gt;&amp;lt;bean id=&quot;">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringMVC基础学习之文件的上传与下载">
<meta property="og:url" content="https://zitongchen.github.io/2017/08/15/SpringMVC基础学习之文件的上传与下载/index.html">
<meta property="og:site_name" content="Tony's Notes">
<meta property="og:description" content="配置MultipartResolver实现文件上传，SpringMVC专门提供了CommonsMultipartResolver组件用于文件上传：

maxUploadSize    文件最大限制，单位是byte
maxInMemorySize     低于这个大小的文件暂存内存中
defaultEncoding    默认编码

&amp;lt;!--文件上传的组件--&amp;gt;&amp;lt;bean id=&quot;">
<meta property="og:updated_time" content="2017-09-16T10:24:07.324Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SpringMVC基础学习之文件的上传与下载">
<meta name="twitter:description" content="配置MultipartResolver实现文件上传，SpringMVC专门提供了CommonsMultipartResolver组件用于文件上传：

maxUploadSize    文件最大限制，单位是byte
maxInMemorySize     低于这个大小的文件暂存内存中
defaultEncoding    默认编码

&amp;lt;!--文件上传的组件--&amp;gt;&amp;lt;bean id=&quot;">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zitongchen.github.io/2017/08/15/SpringMVC基础学习之文件的上传与下载/"/>





  <title> SpringMVC基础学习之文件的上传与下载 | Tony's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://zitongchen.github.io/2017/08/15/SpringMVC基础学习之文件的上传与下载/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avater.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                SpringMVC基础学习之文件的上传与下载
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-15T00:00:00+08:00">
                2017-08-15
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Spring/" itemprop="url" rel="index">
                    <span itemprop="name">Spring</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/08/15/SpringMVC基础学习之文件的上传与下载/" class="leancloud_visitors" data-flag-title="SpringMVC基础学习之文件的上传与下载">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>配置MultipartResolver实现文件上传，SpringMVC专门提供了CommonsMultipartResolver组件用于文件上传：</p>
<ul>
<li>maxUploadSize    文件最大限制，单位是byte</li>
<li>maxInMemorySize     低于这个大小的文件暂存内存中</li>
<li>defaultEncoding    默认编码</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><div class="line"><span class="comment">&lt;!--文件上传的组件--&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"multipartResolver"</span></span></div><div class="line">		<span class="attr">class</span>=<span class="string">"org.springframework.web.multipart.commons.CommonsMultipartResolver"</span>&gt;</div><div class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"defaultEncoding"</span> <span class="attr">value</span>=<span class="string">"utf-8"</span> /&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"maxUploadSize"</span> <span class="attr">value</span>=<span class="string">"10485760000"</span> /&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"maxInMemorySize"</span> <span class="attr">value</span>=<span class="string">"4096"</span> /&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></div><div class="line"><span class="comment">&lt;!--2.静态资源默认servlet配置--&gt;</span></div><div class="line">    <span class="comment">&lt;!--</span></div><div class="line">        1.加入对静态资源处理：js,gif,png</div><div class="line">        2.允许使用“/”做整体映射</div><div class="line">    --&gt;</div><div class="line"><span class="tag">&lt;<span class="name">mvc:default-servlet-handler</span>/&gt;</span></div></pre></td></tr></table></figure>
<p>上传的组件部署需要写上id的值，因为DispatcherServlet类定义好了id的属性值为：multipartResolver</p>
<p>上传需要的jar包：</p>
<ul>
<li>commons-fileupload.jar</li>
<li>commons-io.jar<br>Maven工程的pom.xml依赖：<figure class="highlight xml"><table><tr><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">version</span>&gt;</span>1.3.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">version</span>&gt;</span>2.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
</ul>
<p>上传的Java文件<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="meta">@Controller</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FileUploadController</span> </span>&#123;</div><div class="line">	<span class="meta">@RequestMapping</span>(value=<span class="string">"/upload/uploadfile"</span>, method=RequestMethod.GET)</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">uploadLogin</span><span class="params">()</span></span>&#123;</div><div class="line">		<span class="keyword">return</span> <span class="string">"fileupload"</span>;</div><div class="line">	&#125;</div><div class="line">	<span class="meta">@RequestMapping</span>(value=<span class="string">"/upload/uploadfile"</span>, method=RequestMethod.POST)</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">uploadFile</span><span class="params">(@RequestParam(<span class="string">"imageFile"</span>)</span> MultipartFile imageFile,HttpServletRequest request)</span>&#123;</div><div class="line">		<span class="comment">//获取保存图片的绝对路径（即webapps文件加下的路径）</span></div><div class="line">		String uploadUrl = request.getServletContext().getRealPath(<span class="string">"/"</span>) + <span class="string">"images/"</span>;</div><div class="line">		<span class="comment">//获取文件名</span></div><div class="line">		String filename = imageFile.getOriginalFilename();</div><div class="line">		<span class="comment">//File类是操作目录跟文件的，但不读取文件内容</span></div><div class="line">		File dir = <span class="keyword">new</span> File(uploadUrl);</div><div class="line">		<span class="keyword">if</span>(!dir.exists())&#123;</div><div class="line">			dir.mkdirs();</div><div class="line">		&#125;</div><div class="line">		System.out.println(<span class="string">"文件上传到："</span> + uploadUrl + filename);</div><div class="line">		<span class="comment">//通过路径获取文件信息，若不存在文件，便创建一个</span></div><div class="line">		File targetFile = <span class="keyword">new</span> File(uploadUrl + filename);</div><div class="line">		<span class="keyword">if</span>(!targetFile.exists())&#123;</div><div class="line">			<span class="keyword">try</span>&#123;</div><div class="line">				targetFile.createNewFile();</div><div class="line">			&#125;<span class="keyword">catch</span>(IOException e)&#123;</div><div class="line">				e.printStackTrace(); </div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			<span class="comment">//把文件复制到指定文件内</span></div><div class="line">			imageFile.transferTo(targetFile);</div><div class="line">		&#125; <span class="keyword">catch</span> (IllegalStateException | IOException e) &#123;</div><div class="line">			<span class="comment">// TODO Auto-generated catch block</span></div><div class="line">			e.printStackTrace();</div><div class="line">		&#125;</div><div class="line">      <span class="comment">//返回文件路径</span></div><div class="line">		request.setAttribute(<span class="string">"imgUrl"</span>, request.getContextPath() +<span class="string">"/images/"</span> + filename);</div><div class="line">		<span class="keyword">return</span> <span class="string">"showimg"</span>;</div><div class="line">	&#125;</div><div class="line">  <span class="comment">//多文件上传</span></div><div class="line">	<span class="meta">@RequestMapping</span>(value=<span class="string">"/upload/moreUpload"</span>,method = RequestMethod.POST)</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">moreUpload</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> IOException</span>&#123;</div><div class="line">		<span class="comment">//把request转换为MultipartHttpServletRequest</span></div><div class="line">		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;</div><div class="line">		<span class="comment">//获取包含多个文件的map集合</span></div><div class="line">		Map&lt;String, MultipartFile&gt; files = multipartHttpServletRequest.getFileMap();</div><div class="line">		<span class="comment">//获取保存路径的绝对路径</span></div><div class="line">		String uploadUrl = request.getServletContext().getRealPath(<span class="string">"/"</span>) + <span class="string">"images/"</span>;</div><div class="line">		File dir = <span class="keyword">new</span> File(uploadUrl);</div><div class="line">		<span class="keyword">if</span>(!dir.exists())&#123;</div><div class="line">			dir.mkdirs();</div><div class="line">		&#125;</div><div class="line">		List&lt;String&gt; fileList = <span class="keyword">new</span> ArrayList&lt;String&gt;();</div><div class="line">		<span class="comment">//获取FileMap的值，其类型为MultipartFile</span></div><div class="line">		<span class="keyword">for</span>(MultipartFile file:files.values())&#123;</div><div class="line">			File targetFile = <span class="keyword">new</span> File(uploadUrl + file.getOriginalFilename());</div><div class="line">			<span class="keyword">if</span>(!targetFile.exists())&#123;</div><div class="line">				targetFile.createNewFile();</div><div class="line">			&#125;</div><div class="line">			file.transferTo(targetFile);</div><div class="line">			fileList.add(request.getContextPath() + <span class="string">"/images/"</span> + file.getOriginalFilename());</div><div class="line">		&#125;</div><div class="line">      <span class="comment">//返回文件路径</span></div><div class="line">		request.setAttribute(<span class="string">"imgList"</span>,fileList);</div><div class="line">		<span class="keyword">return</span> <span class="string">"showimg"</span>;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>上传文件页面的form表单的enctype属性为enctype=”multipart/form-data”</p>
<p>Servlet3.0的文件上传,使用到了@MultipartConfig注解：<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * Servlet implementation class UploadImagesServlet</div><div class="line"> */</div><div class="line"><span class="meta">@WebServlet</span>(<span class="string">"/upload"</span>)</div><div class="line"><span class="meta">@MultipartConfig</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UploadImagesServlet</span> <span class="keyword">extends</span> <span class="title">HttpServlet</span> </span>&#123;</div><div class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">1L</span>;</div><div class="line">	<span class="keyword">private</span> String relaName;</div><div class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doGet</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</div><div class="line">		doPost(request, response);</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doPost</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</div><div class="line">		<span class="comment">//设置编码</span></div><div class="line">		response.setContentType(<span class="string">"text/html;charset=utf-8"</span>);</div><div class="line">		request.setCharacterEncoding(<span class="string">"utf-8"</span>);</div><div class="line">		<span class="comment">//获取文件域</span></div><div class="line">		Part part = request.getPart(<span class="string">"imgFile"</span>);</div><div class="line">		<span class="comment">//文件的支持类型</span></div><div class="line">		String[] allowType = &#123;<span class="string">"image/bmp"</span>,<span class="string">"image/gif"</span>,<span class="string">"image/jpeg"</span>,<span class="string">"image/png"</span>&#125;;</div><div class="line">		<span class="keyword">boolean</span> allowed = Arrays.asList(allowType).contains(part.getContentType());</div><div class="line">		<span class="keyword">if</span>(!allowed)&#123;</div><div class="line">			response.getWriter().write(<span class="string">"error|不支持的类型"</span>);</div><div class="line">			<span class="keyword">return</span> ;</div><div class="line">		&#125;</div><div class="line">		<span class="comment">//限制图片大小</span></div><div class="line">		<span class="keyword">if</span>(part.getSize() &gt; <span class="number">5</span> * <span class="number">1024</span> * <span class="number">1024</span>)&#123;</div><div class="line">			response.getWriter().write(<span class="string">"error|图片大小不能超过5M"</span>);</div><div class="line">			<span class="keyword">return</span> ;</div><div class="line">		&#125;</div><div class="line">		<span class="comment">//包含原始文件名的字符串</span></div><div class="line">		String fi = part.getHeader(<span class="string">"content-disposition"</span>);</div><div class="line">		<span class="comment">//获取图片格式</span></div><div class="line">		String fileNameExtension = fi.substring(fi.indexOf(<span class="string">"."</span>),fi.length()-<span class="number">1</span>);</div><div class="line">		<span class="comment">//重定义文件名</span></div><div class="line">		String realName = UUID.randomUUID().toString()+fileNameExtension;</div><div class="line">		<span class="comment">//图片保存位置</span></div><div class="line">		String realPath = getServletContext().getRealPath(<span class="string">"/resources/images"</span>) + <span class="string">"/"</span> + realName;</div><div class="line">		<span class="comment">//保存图片</span></div><div class="line">		part.write(realPath);</div><div class="line">		<span class="comment">//返回响应码</span></div><div class="line">		response.getWriter().write(request.getContextPath() + <span class="string">"/resources/images/"</span> + realName);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>servlet文件下载：<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DownloadImagesServlet</span> <span class="keyword">extends</span> <span class="title">HttpServlet</span> </span>&#123;</div><div class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">1L</span>;</div><div class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doGet</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</div><div class="line">		doPost(request, response);</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doPost</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</div><div class="line">		String dataDirectory = request.getServletContext().getRealPath(<span class="string">"/WEB-INF/data"</span>);</div><div class="line">      	File file = <span class="keyword">new</span> File(dataDirectory,<span class="string">"secret.pdf"</span>);</div><div class="line">      	<span class="keyword">if</span>(file.exists())&#123;</div><div class="line">          response.setContextType(<span class="string">"application/pdf"</span>);</div><div class="line">          response.addHeader(<span class="string">"Content-Disposition"</span>,<span class="string">"attachment;filename=secret.pdf"</span>);</div><div class="line">          <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</div><div class="line">          FileInputStream fis = <span class="keyword">null</span>;</div><div class="line">          BufferedInputSteam bis = <span class="keyword">null</span>;</div><div class="line">          <span class="keyword">try</span> &#123;</div><div class="line">            fis = <span class="keyword">new</span> FileInputStream(file);</div><div class="line">            bis = <span class="keyword">new</span> BufferedInputSteam(fis);</div><div class="line">            OutputSteam os = response.getOutputStream();</div><div class="line">            <span class="keyword">int</span> i = bis.read(buffer);</div><div class="line">            <span class="keyword">while</span> (i != -<span class="number">1</span>)&#123;</div><div class="line">              os.write(buffer, <span class="number">0</span>, i);</div><div class="line">              i = bis.read(buffer);</div><div class="line">            &#125; <span class="keyword">catch</span> (IOException ex)&#123;</div><div class="line">              <span class="comment">//do something</span></div><div class="line">            &#125; <span class="keyword">finally</span> &#123;</div><div class="line">              <span class="keyword">if</span> (bis != <span class="keyword">null</span>) &#123;</div><div class="line">                <span class="keyword">try</span> &#123;</div><div class="line">                  bis.close();</div><div class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">                &#125;</div><div class="line">              &#125;</div><div class="line">              <span class="keyword">if</span> (fis != <span class="keyword">null</span>) &#123;</div><div class="line">                <span class="keyword">try</span> &#123;</div><div class="line">                  fis.close();</div><div class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">                  <span class="comment">//do something</span></div><div class="line">                &#125;</div><div class="line">              &#125;</div><div class="line">            &#125;</div><div class="line">          &#125;</div><div class="line">      	&#125;</div><div class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/springmvc/" rel="tag"># springmvc</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/14/SpringMVC基础学习(一)/" rel="next" title="SpringMVC基础学习(一)">
                <i class="fa fa-chevron-left"></i> SpringMVC基础学习(一)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/16/Java基础--反射/" rel="prev" title="Java基础--反射">
                Java基础--反射 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avater.png"
               alt="Tony" />
          <p class="site-author-name" itemprop="name">Tony</p>
           
              <p class="site-description motion-element" itemprop="description">学习技术，分享技术...</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zitongchen" rel="external nofollow" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2130825"></script>
      <!-- UY END -->
    
  





  



  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("4wyUmphSKE5wrQGHEh5Js0bk-gzGzoHsz", "oTOHrhMuED5U0oqV2KrRMGF0");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  


  
</body>
</html>
